package com.ssyx.aspect;

import com.ssyx.annotation.AutoType;
import com.ssyx.constant.GlobalConstant;
import com.ssyx.exception.SsyxException;
import com.ssyx.model.product.Attr;
import com.ssyx.model.product.AttrGroup;
import com.ssyx.model.product.Category;
import com.ssyx.result.ResultCodeEnum;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

/**
 * 自定义切面类
 */

@Slf4j
@Aspect
@Component
public class AutoTypeAspect {
	
	/**
	 * 切入点
	 */
	@Pointcut("execution(* com.ssyx.controller.*.*(..)) && @annotation(com.ssyx.annotation.AutoType)")
	public void autoFillPointCut() {}
	
	/**
	 * 前置通知
	 */
	@Before("autoFillPointCut()")
	public void autoFill(JoinPoint joinPoint) {
		// 获取操作类型
		MethodSignature signature = (MethodSignature) joinPoint.getSignature();   // 获取方法类型
		String value = signature.getMethod().getAnnotation(AutoType.class).value();// 获取注解对象的操作类型
		log.info("获取注解类型：value:{}", value);
		// 获取方法的参数-实体对象
		Object[] args = joinPoint.getArgs();
		if (args == null || args.length == GlobalConstant.INTEGER_ZERO) {
			log.error("参数不能为空");
			throw new SsyxException(ResultCodeEnum.ILLEGAL_PARAM);
		}
		switch (value) {
			case "AttrGroup":
				AttrGroup attrGroup = (AttrGroup) args[GlobalConstant.INTEGER_ZERO];
				isExits(attrGroup.getName(), attrGroup.getSort());
				break;
			case "Category":
				Category category = (Category) args[GlobalConstant.INTEGER_ZERO];
				isExits(category.getName(), category.getSort());
				break;
			case "Attr":
				Attr attr = (Attr) args[GlobalConstant.INTEGER_ZERO];
				isExits(attr.getName(), GlobalConstant.INTEGER_ONE);
				if (StringUtils.isEmpty(attr.getInputType())) {
					log.error("录入方式不能为空");
					throw new SsyxException(ResultCodeEnum.ILLEGAL_PARAM);
				}
				break;
			default:
				log.error("非法参数");
				throw new SsyxException(ResultCodeEnum.ILLEGAL_PARAM);
		}
	}
	
	private void isExits(String name, Integer sort) {
		if (name.equals(" ") || StringUtils.isEmpty(name)) {
			log.error("名称不能为空");
			throw new SsyxException(ResultCodeEnum.ILLEGAL_PARAM);
		}
		if (StringUtils.isEmpty(sort) || sort < GlobalConstant.INTEGER_ZERO) {
			log.error("排序不能为空");
			throw new SsyxException(ResultCodeEnum.ILLEGAL_PARAM);
		}
		
	}
}
